<?php

namespace Home\Controller;


use Think\Controller;
use Home\Model\B2cMemberAddrsModel;
use Think\Exception;


class PayController extends Controller
{
    // 默认 会员ID
    //public $member_id = 714;
    public $obj;
    public function __construct(){
        parent::__construct();
        ini_set('date.timezone','Asia/Shanghai');
    }

    /**
     *
     */
    public function index()
    {
        die('11');
    }

    /**
     * 微信支付
     */
    public function weixinpay(){

        $order = I('id') ? I('id') : $this->error('参数错误');
        //dump($order);
        //查询order_num表
        $order_money = M('b2c_order_num')->where(['order_num' => $order])->find()['cost_money'];
        //dump($order_money);die;
        if(!$order_money){
            $this->error('支付金额为空');
        }
        //订单支付金额
        $money = $order_money * 100;
        Vendor('WeixinPay.WxPayment');
        $WxPay_obj = new \WxPayment();
        $data = $WxPay_obj->starWxPayment($order,$money);
       // dump($data);die;
        /*if(isset($data['error'])){
            $this->error($data['msg']);
        }*/
        $this->assign('data',$data);
        $this->assign('order_num',$order);
        $this->assign('order_money',$order_money);
        $this->display();
    }

    /**
     * 易极付(微信支付)
     */
    public function yijipay(){
        $order = I('id') ? I('id') : $this->error('参数错误');
        $config = array(
            'partnerId'     =>C('PARTNER_ID'),
            'md5Key'        =>C('MD5_KEY'),
            'gatewayUrl'    =>C('GATEWAY_URL'),
            'payNotieyUrl'  =>C('PAY_NOTIFY_URL'),
            'payRenturnUrl' =>C('PAY_RENTURN_URL'),
        );
        //用户id
        $member_id = session('userInfo')['member_id'];
        $order_money = M('b2c_order_num')->where(['order_num' => $order])->find()['cost_money'];
        //dump($order_money);die;
        if(!$order_money){
            $this->error('支付金额为空');
        }
        //订单支付金额
        $money = $order_money;
        //openID
        $openId = session('userInfo')['openid'];
        if(!$openId){
            $this->error('请先登录！');
        }
        //dump($openId);die;
        Vendor('Yijifu.yijipayPayment');
        $yjp_obj = new \yijipayPayment();
        $yjp_obj->commandPayTradeCreatePay($order,$member_id,$money,$config,$openId);


    }

    /**
     * 易极付同步通知
     */
    public function yijipayReturn(){
        $params = $_GET;
        $config = array(
            'partnerId'     =>C('PARTNER_ID'),
            'md5Key'        =>C('MD5_KEY'),
            'gatewayUrl'    =>C('GATEWAY_URL'),
            'payNotieyUrl'  =>C('PAY_NOTIFY_URL'),
            'payRenturnUrl' =>C('PAY_RENTURN_URL'),
        );
        import('Vendor.Yijifu.yijipay.YijipayClient');
        $client = new \YijipayClient($config);

        if($client->verify($params)){
            //dump($params);
            //验签成功
            //正确日志
            $log_data = ['order_id' => $params['merchOrderNo'],'transaction_id'=>$params['orderNo'],'alttime' => time(),'log_type' => 'success','order_type'=>2,'log_text' => $params['resultMessage'],'addon'=>json_encode($params)];
            $this -> orderPayLog($log_data);
            //echo M()->_sql();die;
            //查询order_num
            $data = M('b2c_orders')->where(['order_num' => $params['merchOrderNo']])->select();
            if(!$data){
                //  入日志表
                $log_data = ['order_id' => $params['merchOrderNo'],'alttime' => time(),'log_type' => 'failure','order_type'=>2,'log_text' => '支付订单号不存在！'];
                $this -> orderPayLog($log_data);
                return;
            }

            //判断是否锁定，锁定说明正在被其它线程处理中或处理完成
            $model = M();
            $model->startTrans();
            try{
                $nums = $model->query("SELECT * FROM `sdb_b2c_order_num`WHERE order_num='".$params['merchOrderNo']."' LOCK IN SHARE MODE");
                //dump($nums);die;
                if($nums){
                    if($nums[0]['status'] == 1){
                        $this->redirect('Pay/paySuccess',['order_num' => $params['merchOrderNo'],'type'=>4]);die;
                    }elseif($nums[0]['status'] == 2){
                        $this->redirect('Pay/payFail',['order_num' => $params['merchOrderNo'],'type'=>4]);die;
                    }
                }

                foreach($data as $k1 => $v1){
                    //判断是否已运行过（微信异步时请求时间太短）
                    if($v1['pay_status'] != '1'){
                        $stat = $this->saveTable($v1,$params['merchOrderNo'],$params['orderNo'],4);
                        if($stat === false){
                            throw new Exception(false);
                        }
                    }
                }
                //修改为已支付
                $stat_num = M('b2c_order_num ')->where(['order_num' => $params['merchOrderNo']])->save([
                    'transaction_id' => $params['orderNo'],
                    'pay_money' => $params['tradeAmount'],
                    'status' => 1,
                ]);
                if($stat_num === false){
                    throw new Exception(false);
                }
                $model->commit();
                //重定向
                $this->redirect('Pay/paySuccess',['order_num' => $params['merchOrderNo'],'type'=>4]);
            }catch (\Exception $e){
                $model->rollback();
            }
        }else{
            //失败记录订单日志
            $log_data = [
                'order_id' => $params['merchOrderNo'],
                'transaction_id'=>$params['orderNo'],
                'alttime' => time(),
                'log_type' => 'failure',
                'order_type'=>2,
                'log_text' => $params['resultMessage'],
                'addon'=>json_encode($params)
            ];
            $this -> orderPayLog($log_data);
            //重定向
            $this->redirect('Pay/payFail',['order_num' => $params['merchOrderNo'],'type'=>4]);
        }
    }

    /**
     * 易极付异步通知
     */
    public function yijipayNotify(){
        $params = $_POST;
        file_put_contents("log/".date('Y-m-d')."payOrder.txt", date ( "Y-m-d H:i:s" ) . "  " . json_encode($params) . "<br/>\n", FILE_APPEND );
        exit('success');
        $params = $_POST;
        $config = array(
            'partnerId'     =>C('PARTNER_ID'),
            'md5Key'        =>C('MD5_KEY'),
            'gatewayUrl'    =>C('GATEWAY_URL'),
            'payNotieyUrl'  =>C('PAY_NOTIFY_URL'),
            'payRenturnUrl' =>C('PAY_RENTURN_URL'),
        );
        import('Vendor.Yijifu.yijipay.YijipayClient');
        $client = new \YijipayClient($config);
        if($client->verify($params)){
            //验签成功
            //正确日志
            $log_data = ['order_id' => $params['merchOrderNo'],'transaction_id'=>$params['orderNo'],'alttime' => time(),'log_type' => 'success','order_type'=>2,'log_text' => $params['resultMessage'],'addon'=>json_encode($params)];
            $this -> orderPayLog($log_data);
            //查询order_num
            $data = M('b2c_orders')->where(['order_num' => $params['merchOrderNo']])->select();
            if(!$data){
                //  入日志表
                $log_data = ['order_id' => $params['merchOrderNo'],'alttime' => time(),'log_type' => 'failure','order_type'=>2,'log_text' => '支付订单号不存在！'];
                $this -> orderPayLog($log_data);
                return;
            }
            //判断是否锁定，锁定说明正在被其它线程处理中或处理完成
            $model = M();
            $model->startTrans();
            try{
                $nums = $model->query("SELECT * FROM `sdb_b2c_order_num`WHERE order_num='".$params['merchOrderNo']."' LOCK IN SHARE MODE");
                if($nums){
                    if($nums[0]['status'] == 1){
                        die('success');
                    }
                }

                foreach($data as $k1 => $v1){
                    //判断是否已运行过（微信异步时请求时间太短）
                    if($v1['pay_status'] != '1'){
                        $stat = $this->saveTable($v1,$params['merchOrderNo'],$params['orderNo'],4);
                        if($stat === false){
                            throw new Exception(false);
                        }
                    }
                }
                //修改为已支付
                $stat_num = M('b2c_order_num ')->where(['order_num' => $params['merchOrderNo']])->save([
                    'transaction_id' => $params['orderNo'],
                    'pay_money' => $params['tradeAmount'],
                    'status' => 1,
                ]);
                if($stat_num === false){
                    throw new Exception(false);
                }
                $model->commit();
                //重定向
                die('success');
            }catch (\Exception $e){
                $model->rollback();
            }
        }else{
            //失败记录订单日志
            //file_put_contents("payError.txt", date ( "Y-m-d H:i:s" ) . "  " . $xml . "<br/>\n", FILE_APPEND );
            $log_data = [
                'order_id' => $params['merchOrderNo'],
                'transaction_id'=>$params['orderNo'],
                'alttime' => time(),
                'log_type' => 'failure',
                'order_type'=>2,
                'log_text' => $params['resultMessage'],
                'addon'=>json_encode($params)
            ];
            $this -> orderPayLog($log_data);
        }
    }

    /**
     * 微信成功返回
     */
    public function paySuccess(){
        $time = time();
        $order_num = I('get.order_num');
        $type = I('get.type',0);
        //添加到队列
        if($type == 1){
            $this->queue(['order_num'=>$order_num,'create_time'=>$time,'queue_lock' => 0,'pay_id'=>$type]);
        }

        if(!$order_num){
            $this->error('参数不对！');
        }
        $data = M('b2c_order_num a')
            ->field('a.*,p.`name`')
            ->join("left join ".C('DB_PREFIX')."b2c_payment p on p.id = a.pay_id")
            ->where(['order_num'=>$order_num])->find();

        $order_data = M('b2c_orders o')->where(['order_num'=>$order_num])
            ->field('o.*,s.`province`')
            ->join("left join ".C('DB_PREFIX')."webpos_local_store s on s.local_id = o.local_id")
            ->select();
        $msgTime = array();

        $coupon = '';
        $t = 0;
        foreach($order_data as $k1 => $v1){
            // 微信支付消息推送给上级会员
            WeixinPayPushToFatherMember(session('userInfo')['member_id'], $v1['local_id'], $v1['order_id']);

            $save['ship_time'] = $this->predictionTime($time,$v1['shipping_id'],$v1['ship_area'],$v1['province']);
            $msgTime[$v1['order_id']] = ['type' => $v1['shipping_id'],'msg' => $save['ship_time']];
            $status = M('b2c_orders')->where(['order_id'=>$v1['order_id']])->save($save);
            if($status === false){
                $this->error('失败！');
            }
            //优惠劵
            if(!empty($v1['order_promotions'])){
                $order_promotions = unserialize($v1['order_promotions']);
                foreach($order_promotions['gift_coupon'] as $v2){
                    $coupon .= $this->coupon($v2).'、';
                }
            }
            //奖金支付 name 更改
            if($v1['bonus_pay']>0 && $t == 0){
                $data['name'] = $v1['payment'];
                $t++;
            }
            $data['pay_money'] += $v1['bonus_pay'];


        }
        if($coupon){
            $coupon = trim($coupon,'、');
        }
        $msgTime = M('b2c_orders')->where(['order_num'=>$order_num])
            ->field('order_id,shipping_id,ship_time')
            ->select();
        //dump($msgTime);
        $this->assign('coupon',$coupon);
        $this->assign('data',$data);
        $this->assign('msgTime',$msgTime);
        $this->display();
    }

    /**
     * 查询优惠劵
     */
    public function coupon($id){
        return M('b2c_discount_coupon_code dcc')->field("dc.name")
                ->join("left join ".C('DB_PREFIX')."b2c_discount_coupon dc on dc.local_id = dcc.local_id and dc.id = dcc.discount_coupon_id")
                ->where(['dcc.id' => $id])
                ->find()['name'];
    }

    /**
     * 配送预估到达时间
     * @param $time 支付时间戳
     * @param $type 物流类型 1-怡臣速配、2-第三方快递、3-门店自提
     * $ship_area 收货地址
     * $province 门店发货地址
     */
    public function predictionTime($time,$type,$ship_area='',$province=''){
        $msg = '';
        $minDate = strtotime(date('Y-m-d',$time)." 8:00:00");
        $maxDate = strtotime(date('Y-m-d',$time)." 20:00:00");
        //怡臣速配
        if($type == 1){
            if(($minDate <= $time) && ($time < $maxDate)){
                $msg = '预计'.date('Y-m-d H:i',$time+7200).'送达';
            }else if($time < $minDate){
                $msg = '预计'.date('Y-m-d',$time).'10:00:00前送达';
            }else if($time > $maxDate){
                $msg = '预计'.date('Y-m-d',$time+86400).'10:00:00前送达';
            }
        }
        //第三方快递
        else if($type == 2){
            $ship_areas = explode('/',$ship_area);
            //判断是否同城
            if($ship_areas[0] == $province){
                $msg = '预计'.date('Y-m-d',$time+172800).'日前到达';
            }else{
                $msg = '预计'.date('Y-m-d',$time+432000).'日前到达';
            }
        }
        //门店自提
        else if($type == 3){
            $msg = '预计2小时后可在自提点自提';
        }
        return $msg;
    }

    /**
     * 失败返回
     * $type 支付方式。注意：占时只有微信可以查询订单状态，其它支付方式暂时不考虑
     */
    public function payFail(){
        // todo 查询微信那边的订单状态
        $order_num = I('get.order_num');
        if(!$order_num ){
            $this->error('参数不对！');
        }
        $type = I('get.type',0);
        //添加到队列
        if($type == 1){
            $this->queue(['order_num'=>$order_num,'create_time'=>time(),'queue_lock' => 0,'pay_id'=>$type]);
        }

        $status = M('b2c_order_num')->where(['order_num'=>$order_num])->save(['status'=>2]);
        $this->assign('order_num',$order_num);
        $this->display();
    }

    /**
     * 微信支付返回
     */
    public function returnPay(){
        //exit('SUCCESS');
        $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        //file_put_contents("newfile.txt", $xml);
        $xmlArr = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $out_trade_no = $xmlArr['out_trade_no']; //订单号
        $total_fee = $xmlArr['total_fee']/100; //回调回来的xml文件中金额是以分为单位的
        $result_code = $xmlArr['result_code']; //状态
        $transaction_id = $xmlArr['transaction_id']; //微信支付单号
        if($result_code == 'SUCCESS'){ //数据库操作
            //正确日志
            $log_data = ['order_id' => $out_trade_no,'transaction_id'=>$transaction_id,'alttime' => time(),'log_type' => 'success','order_type'=>2,'log_text' => $xmlArr['return_msg'],'addon'=>$xml];
            $this -> orderPayLog($log_data);
            //查询order_num
            $data = M('b2c_orders')->where(['order_num' => $out_trade_no])->select();
            if(!$data){
                //  入日志表
                $log_data = ['order_id' => $out_trade_no,'alttime' => time(),'log_type' => 'failure','order_type'=>2,'log_text' => '支付订单号不存在！'];
                $this -> orderPayLog($log_data);
                exit;
            }

            //判断是否锁定，锁定说明正在被其它线程处理中或处理完成
            $model = M();
            $model->startTrans();
            try{
                $nums = $model->query("SELECT * FROM `sdb_b2c_order_num`WHERE order_num='".$out_trade_no."' LOCK IN SHARE MODE");
                if($nums){
                    if($nums[0]['status'] == 1){
                        die('SUCCESS');
                    }
                }

                foreach($data as $k1 => $v1){
                    // 分销
                    $shoppingAward = shoppingAward($v1['member_id'], $v1['local_id'], $v1['order_id']);
                    if ($shoppingAward == false) {
                        throw new Exception(false);
                    }
                    //判断是否已运行过（微信异步时请求时间太短）
                    if($v1['pay_status'] != '1'){
                        $stat = $this->saveTable($v1,$out_trade_no,$transaction_id,1);
                        if($stat !== true){
                            throw new Exception($stat);
                        }
                    }
                }
                //修改为已支付
                $stat_num = M('b2c_order_num ')->where(['order_num' => $out_trade_no])->save([
                    'transaction_id'=>$transaction_id,
                    'pay_money' => $total_fee,
                    'status' => 1,
                ]);
                if($stat_num === false){
                    throw new Exception(false);
                }
                $model->commit();
                //重定向
                die('SUCCESS');//返回成功给微信端 一定要带上不然微信会一直回调8次
            }catch (\Exception $e){
                $model->rollback();
                $stat = $e->getMessage();
                $data = [
                    'rel_id' => $out_trade_no,
                    'op_id' => '',
                    'alttime' => time(),
                    'behavior' => 'payments',
                    'result' => 'FAILURE',
                ];
                // 入日志表
                if($stat['type'] == 0){
                    $data['log_text'] = '订单号不存在！';
                    $this -> orderLog($data);
                }
                if($stat['type'] == 1){
                    $data['log_text'] = '修改订单状态失败！';
                    $this -> orderLog($data);
                }
                if($stat['type'] == 2){
                    $data['log_text'] = '添加账目流水失败！';
                    $this -> orderLog($data);
                }
                if($stat['type'] == 3){
                    $data['log_text'] = '更新销量失败！';
                    $this -> orderLog($data);
                }
                if($stat['type'] == 4){
                    $data['log_text'] = '更新物流受理失败！';
                    $this -> orderLog($data);
                }
                if($stat['type'] == 5){
                    $data['log_text'] = '新增会员与店铺关系失败！';
                    $this -> orderLog($data);
                }
                if($stat['type'] == 6){
                    $data['log_text'] = '赠送优惠券失败';
                    $this -> orderLog($data);
                }
            }
        }else{
            //失败记录订单日志
            //file_put_contents("payError.txt", date ( "Y-m-d H:i:s" ) . "  " . $xml . "<br/>\n", FILE_APPEND );
            $log_data = [
                'order_id' => $out_trade_no,
                'transaction_id'=>$transaction_id,
                'alttime' => time(),
                'log_type' => 'failure',
                'order_type'=>2,
                'log_text' => $xmlArr['return_msg'],
                'addon'=>$xml
            ];
            $this -> orderPayLog($log_data);
            return;
        }
    }

    /**
     * 支付成功后的处理
     * @param $order_data 订单数据
     * @return bool
     */
    public function saveTable($order_data,$out_trade_no,$transaction_id,$payment_id){
        if(!$order_data['order_id']){
            //入日志表
            $log_data = ['order_id' => $order_data['order_id'],'alttime' => time(),'log_type' => 'failure','log_text' => '订单号不存在！'];
            $this -> orderPayLog($log_data);
            return ['status' => false,'type' => 0];
        }

        $save_order = [
            'pay_status' => '1',
            'last_modified' => time(),
            'order_msg' => '待发货',
            'status' => 'active',
        ];
        $order_status = M()->table('sdb_b2c_orders')->where(['order_id' => $order_data['order_id']])->save($save_order);
        if($order_status === false){
            return ['status' => false,'type' => 1];
        }
        // pay_type：1-微信；bills_source_id：1-订单；bill_type：payments-支付
        //账目流水
        $bill_data = [
            'transaction_id' => $transaction_id,
            'bill_id' => $out_trade_no,
            'local_id' => $order_data['local_id'],
            'payment_id' => $payment_id,
            'bill_type' => 'payments',
            'bills_source_id' => 1,
            'money' => $order_data['total_amount'],
            'cost_freight' => $order_data['cost_freight'],
            'payed' => $order_data['payed'],
            'total_amount' => $order_data['total_amount'],
            'createtime' => $order_data['createtime'],
            'paymethod_id' => $order_data['paymethod_id'],
            'cost_item' => $order_data['cost_item'],
            'time' => time(),
            'member_id' => $order_data['member_id'],
            'order_id' => $order_data['order_id'],
            'bonus_money' => $order_data['bonus_pay'],
        ];
        $bill_status = M()->table('sdb_b2c_bills')->add($bill_data);
        if($bill_status === false){
            return ['status' => false,'type' => 2];
        }
        //更新销量
        //根据订单号查询订单详情的货品
        $product_data = M('b2c_order_items')->field('product_id,nums')->where(['order_id' => $order_data['order_id']])->select();
        //根据货品修改店铺商品的销量
        foreach($product_data as $k1 => $v1){
            $num = M('b2c_store_product')->where(['product_id' => $v1['product_id']])->find()['sales_num'];
            $sales_stat = M('b2c_store_product')->where(['product_id' => $v1['product_id']])->save(['sales_num' => $num + $v1['nums']]);
            if($sales_stat === false){
                return ['status' => false,'type' => 3];
            }
        }
        //成功，入日志表
        $log_data = [
            'rel_id' => $order_data['order_id'],
            'op_id' => $order_data['member_id'],
            'op_name' => $order_data['ship_mobile'],
            'alttime' => time(),
            'behavior' => 'payments',
            'result' => 'SUCCESS',
            'log_text' => '订单支付成功！'
        ];
        $this -> orderLog($log_data);
        //物流受理
        $delivery_data = [
            'order_id' => $order_data['order_id'],
            'local_id' => $order_data['local_id'],
            'item_type' => '1',
            'create_time' => time(),
        ];
        $delivery_stat = M('b2c_delivery_process')->add($delivery_data);
        if($delivery_stat === false){
            return ['status' => false,'type' => 4];
        }
        //购买商品成功后，此会员变为该店铺的会员
        $s_u_data = M('b2c_store_user')->where(['member_id'=>$order_data['member_id'],'local_id'=>$order_data['local_id']])->find();
        if(!$s_u_data){
            $user_data = ['member_id'=>$order_data['member_id'],'local_id'=>$order_data['local_id'],'create_time'=>time(),'status'=>'1'];
            $user_stat = M('b2c_store_user')->add($user_data);
            if($user_stat === false){
                return ['status' => false,'type' => 5];
            }
        }

        //赠送优惠劵
        $order_data1 = unserialize($order_data['order_promotions']);
        if(!empty($order_data1)){
            foreach ($order_data1['gift_coupon'] as $gk=>$gcItem){
                $isGiftCoupon =   M('b2c_discount_coupon_code')->where(['id'=>$gcItem])->save(['member_id'=>$order_data['member_id']]);
                //var_dump($isGiftCoupon);exit;
                if($isGiftCoupon === false){
                    return ['status' => false,'type' => 6];
                }
            }
        }
        return true;
    }

    /**
     * 赠送优惠劵
     * @param $order_data 订单数据
     * @return bool
     */
    public function donateConpou($order_data){
        $data = unserialize($order_data['order_promotions']);
        if(empty($data['gift_coupon'])){
            return true;
        }
        foreach ($data['gift_coupon'] as $gk=>$gcItem){
            $isGiftCoupon =   M('b2c_discount_coupon_code')->save(['id'=>$gcItem,'member_id'=>$order_data['member_id']]);
            //var_dump($isGiftCoupon);exit;
              if($isGiftCoupon === false){
                  return false;
              }
        }
    }

    /**
     * 订单日志
     * @param $data
     * @return mixed
     */
    public function orderLog($data){
        $stat = M('b2c_order_log')->add($data);
//        if($stat === false){
//            $data = json_encode($data);
//            //file_put_contents("log/".date('Y-m-d')."payOrder.txt", date ( "Y-m-d H:i:s" ) . "  " . $data . "<br/>\n", FILE_APPEND );
//            $this->addText("log/".date('Y-m-d')."payOrder.txt",$data);
//        }
        return $stat;
    }
    /**
     * 支付日志
     * @param $data
     * @return mixed
     */
    public function orderPayLog($data){
        $stat = M('b2c_order_pay_log')->add($data);
//        if($stat === false){
//            $data = json_encode($data);
//            //file_put_contents("log/".date('Y-m-d')."payment.txt", date ( "Y-m-d H:i:s" ) . "  " . $data . "<br/>\n", FILE_APPEND );
//            $this->addText("log/".date('Y-m-d')."payment.txt",$data);
//        }
        return $stat;
    }

    /**
     * 查询订单状态
     */
    public function orderQuery(){
        $this->display();
    }

    public function doOrderQuery($transaction_id,$out_trade_no){
        $transaction_id = I('transaction_id','');
        $out_trade_no = I('out_trade_no','');
        Vendor('WeixinPay.WxPayment');
        $WxPay_obj = new \WxPayment();
        $data = $WxPay_obj->orderQuery($transaction_id,$out_trade_no);
        dump($data);
    }

    /**
     * 添加到队列
     * @param $data
     * @return mixed
     */
    public function queue($data){
        $s = M('b2c_order_num_queue')->where(['order_num'=>$data['order_num']])->find();
        if($s){
            return false;
        }
        return M('b2c_order_num_queue')->add($data);
    }

    /**
     * $order_num,$type
     */
    public function payLoading(){
        $order_num = I('order_num');
        $type = I('pay_type');
        $this->assign('order_num',$order_num);
        $this->assign('pay_type',$type);
        $this->display();
    }

    /**
     * 检查订单状态
     */
    public function inspectOrder(){
        $order_num = I('post.order_num','');
        if(!$order_num){
            $this->ajaxReturn(['status' => false,'msg' => '未知错误，请联系管理员！','type' => 0]);
        }
        $data = M('b2c_order_num')->where(['order_num' => $order_num])->find();
        //exit(json_encode(M()->_sql()));
        if($data['status'] == 1){
            $this->ajaxReturn(['status' => true,'msg' => '','type' => 1]);
        }elseif($data['status'] == 2){
            $this->ajaxReturn(['status' => true,'msg' => '','type' => 2]);
        }else{
            $this->ajaxReturn(['status' => true,'msg' => '','type' => 0]);
        }
    }

    /**
     * @param $filename 文件名
     * @param $content  写入内容
     */
    public function addText($filename,$content){
        $filePath= $filename;
        $handle=fopen($filePath,"a+");

        $str=fwrite($handle,$content."\r\n");

        fclose($handle);
    }
    public function __destrcut(){
        parent::__destruct();
        unset($this->obj);
        //unset($this->member_id);
    }


}